#!/usr/bin/env python

import app
import json
import urllib
import urllib2

from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

class Hayate(object):
    '''Hayate Class
    
    @author Julot <andy.julot@gmail.com>
    @since Tuesday, May 08, 2012. 05:31 PM'''
    
    @property
    def host(self):
        return app.Config().Read('Rest/Host', 'ashitahadochida.site11.com')
    
    def _open(self, request):
        request.add_header('X_REST_USERNAME', 'rest-user@longarch')
        request.add_header('X_REST_PASSWORD', 'YagamiHayate')
        try:
            data = urllib2.urlopen(request).read()
            pos = data.find('<!--')
            if pos > 0:
                data = data[:pos]
            r = json.loads(data)
        except:
            r = False
        return r
    
    def get(self, action):
        url = 'http://%s/%s' % (self.host, action)
        register_openers()
        request = urllib2.Request(url)
        return self._open(request)
    
    def post(self, action, params, file=None):
        url = 'http://%s/%s' % (self.host, action)
        register_openers()
        if file:
            params['images[1]'] = open(file, 'rb')
            data, headers = multipart_encode(params)
            request = urllib2.Request(url, data, headers)
        else:
            data = urllib.urlencode(params)
            request = urllib2.Request(url, data)
        return self._open(request)
        
